$(document).ready(function ($) {
    $('input[name="chefa_retposhto"], input[name="chefa_telefonanumero"]').on('focusout', ajax_validation);
    $('select[name="kodo_telefonanumero"]').on('change', ajax_validation);

    if(typeof formatter !== "undefined" && !formatter) {
        console.log('Siriuso Formatter disabled!');
    } else {
        SiriusoFormatter();
    }
});

function checkSelection() {
    if($('.registrado_selection_checkbox > input[type="checkbox"]:checked').length && !$('.bad-value').length){
        $('button.submit').removeAttr('disabled');
    } else {
        $('button.submit').attr('disabled', 'disabled');
    }
}

function ajax_validation() {
    let target = $(this);
    target = target.attr('name') === 'kodo_telefonanumero' ? $('input[name="chefa_telefonanumero"]') : target;

    if(!target.val().length || target.val().match(/^[_]+$/)) {
        target.removeClass('good-value').addClass('bad-value');
        return;
    }

    let value = target.attr('name') === "chefa_retposhto" ? target.val() :
        $('select[name="kodo_telefonanumero"] option:selected').text() + target.val();

    $.ajax({
        url: window.location.href,
        type: 'POST',
        async: true,
        cache: false,
        dataType: 'json',
        processData: true,
        data: {
            csrfmiddlewaretoken: getCookie('csrftoken'),
            type: target.prop('name'),
            value: value
        }
    })
        .done(function (response) {
            let res_value = response.value;
            let cond = true;

            if(response.type === 'chefa_telefonanumero') {
                let tel_code = $('select[name="kodo_telefonanumero"] option:selected').text();
                cond = (tel_code === response.value.substring(0,tel_code.length ));
                res_value = res_value.replace(tel_code, '');
            }

            if($('input[name="' + response.type + '"]').val() === res_value && cond) {
                if(response.status) {
                    target.removeClass('bad-value');
                    target.addClass('good-value');
                    checkSelection();
                } else {
                    target.removeClass('good-value');
                    target.addClass('bad-value');
                    checkSelection()
                }
            }
        })
        .fail(function (jqXHR, textStatus){
            console.log("Request failed: " + textStatus);
        });
}